/**
 *  Copyright 2011 Marco Berri - marcoberri@gmail.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 **/
package com.url;

import com.utils.StringUtil;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author marco
 */
public class Qrcode extends com.Base {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {



        if (isIpNullOrSpam(request.getRemoteAddr())) {
            return;
        }

        String data = request.getRequestURI().replaceAll(request.getContextPath(), "").replaceAll("/q/", "");


        if (StringUtil.isNullOrEmpty(data)) {
            fatal("parametro data per url " + request.getRequestURI() + "non valido");
            return;
        }


        String id = null;
        try {

            Statement stat = this.conn_url.createStatement();

            ResultSet rs = stat.executeQuery("select id,url from url where id='" + data + "'");

            if (rs.next()) {
                id = rs.getString("id");
            }

            rs.close();
            stat.close();

        } catch (SQLException e) {
            fatal("SQLException: " + e.getMessage(), e);
            return;
        }

        if (id == null) {
            fatal("Valore non trovato nel db per url " + request.getRequestURI());
            return;
        }

        File image = new File(this.path_app_root + "/" + this.conf.getQrcode().getStorage() + "/" + "/" + id + ".png");
        if (!image.exists()) {
            fatal("Non è presente l'immagine :" + image);
            response.sendError(response.SC_NOT_FOUND);
            return;
        }


        saveStatsQrcode(request, id);

        byte[] newImage = org.apache.commons.io.FileUtils.readFileToByteArray(image);

        response.setContentType("image/png");
        response.setContentLength(newImage.length);
        response.getOutputStream().write(newImage);
        response.getOutputStream().close();

        //vedo di salvare le statistiche di chiamata in qualche modo
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);


    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);


    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";

    }// </editor-fold>
}
